# -*- coding =utf-8 -*-
# @time:2022/10/5
import json
import fasttext
import jieba
import codecs  # codecs专门用作编码转换
import matplotlib.pyplot as plt
from wordcloud import WordCloud

def main():
    #加载数据
    def load_data(data_path):

        with open(data_path) as f:
            data = json.load(f)
        return data

    texts = load_data('./bc.json')

    stopwords = [w.strip() for w in codecs.open("train/stopwords_comment.txt", "r", "utf-8").readlines()]
    classifier = fasttext.train_supervised('train/train_data.txt', label_prefix="__label__", min_count=1, epoch=20)

    cloud_texts = str(texts).replace('\n', ' ').replace('\r', '')
    cloud_texts = ' '.join(w for w in jieba.cut(cloud_texts) if w not in stopwords)

    word_cloud = WordCloud(font_path='simsun.ttc', background_color='white', stopwords=stopwords, width=600, height=600)  # 可选 mask=graph 指定词云的形状

    word_cloud.generate(cloud_texts)
    # word_cloud.to_file('wordcloud.png')
    plt.subplots(figsize=(12, 8))
    plt.imshow(word_cloud)
    plt.axis('off')
    # plt.show()
    word_cloud.to_file('./templates/edg.png')

    #处理数据
    comment = []

    for i in texts:
        text = i.replace('\n', ' ').replace('\r', '')
        text = ' '.join(w for w in jieba.cut(text) if w not in stopwords)
        label_test = classifier.predict(text)
        comment.append(label_test[0][0])
        #print(i + "  " + text)
        #print(label_test[0][0])

    positive = []
    negative = []
    neutral = []

    for i in range(len(comment)):
        if comment[i] == "__label__positive":
            positive.append(texts[i])
        elif comment[i] == "__label__negative":
            negative.append(texts[i])
        else:
            neutral.append(texts[i])
    #饼图
    # plt.rcParams['font.sans-serif'] = ['SimHei']
    # plt.rcParams['axes.unicode_minus'] = False

    # pie_labels = 'positive','negative','neutral'
    # plt.pie([len(positive),len(negative), len(neutral)],labels=pie_labels,autopct='%1.2f%%',shadow=True)
    #
    # plt.show()
    result ={"positive":positive,"negative":negative,"neutral":neutral}
    print(result)
    return result

if __name__ == '__main__':
    main()